<?php
namespace WXAPI\Controller;

use Think\Page;

class SupplierController extends BaseController {
    public $begin;
    public $end;
    /*
     * 初始化操作
     */
    public function _initialize() {
        parent::_initialize();
        $timegap = I('timegap');

        $timegap = str_replace('+',' ',$timegap);
        //echo $timegap;
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = $gap[0];
            $end = $gap[1];
        }else{
            $lastweek = date('Y-m-d H:i',strtotime("-2 day"));//2天前
            $begin = I('begin',$lastweek);
            $end =  I('end',date('Y-m-d H:i'));
        }
        $this->begin = strtotime($begin);
        $this->end = strtotime($end);
    }

    /**
     * 初始化数据
     * @return void
     */
    public function index(){
        $config_arr = M('config')->select();
        $resutl = [];
        foreach ($config_arr as $value){
            if($value['name'] == 'store_logo'){
                $value['value'] = SITE_URL.$value['value'];
                $resutl[$value['name']] = $value['value'];
            }
            if($value['name'] == 'store_name'){
                $value['value'] = $value['value'].'供货端';
                $resutl[$value['name']] = $value['value'];
            }

        }

        exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$resutl)));
    }


    /**
     * 司机登录
     * @return void
     */
    public function login(){
        $username = I('username');
        $password = I('password');

        if(!$username || !$password){
            $result= array('status'=>0,'msg'=>'请填写账号或密码');
        }
        $seller = M('seller a')->field('a.*,b.fenbu_id')->join('ty_store b on a.store_id=b.store_id')->where(array('a.seller_name' => $username))->find();
        
        $user_id = $seller['user_id'];
        $pass = 0;
        $user = M('users')->where("user_id='{$user_id}' ")->find();
        $password1 = encrypt($password);
        $password2 = tlc_hash($password,$user['salt']);
        $password3 = [$password1,$password2];
        if(in_array($user['password'],$password3)){
            $pass = 1;
        }
        if(!$seller || !$user){
            $result = array('status'=>-1,'msg'=>'账号不存在!');
        }elseif(!$pass){
            $result = array('status'=>-2,'msg'=>'密码错误!');
        }elseif($user['is_lock'] == 1){
            $result = array('status'=>-3,'msg'=>'账号异常已被锁定！！！');
        }else{
            $store = M('store')->where(['user_id'=>$user['user_id']])->find();
            if($store && $store['store_state']){
                //查询用户信息之后, 查询用户的登记昵称
                $user['token'] = md5(time().mt_rand(1,999999999));
                $user['store_id'] = $store['store_id'];
                $user['store_name'] = $store['store_name'];
                M('users')->where("user_id = {$user['user_id']}")->save(array('token'=>$user['token'],'last_login'=>time(),'store_id'=>$store['store_id']));
                $result = array('status'=>1,'msg'=>'登陆成功','result'=>$user);
            }else{
                $result = array('status'=>-4,'msg'=>'找不到店铺或店铺已被锁定！！！');
            }

        }


        if($result['status'] != 1)
            exit(json_encode($result));


        exit(json_encode($result));

    }


    /**
     * 获取订单单列表
     * @return void
     */
    public function getOrderList()
    {
        $p = I('page',0);
        $user_id = I('user_id');
        $type = I('type');
        $keys = I('keys');

        $store = M('store')->where(['user_id'=>$user_id])->find(); //查询司机信息
        if($store && $store['store_state']){
            $condition = [];
            $condition['a.order_status'] = ['in','0,1,2'];
            $keys ? $condition['a.order_sn|b.company|b.mobile'] = ['like','%'.$keys.'%'] : false;
            if($type == 1){ //未配送
                $condition['a.jian_count'] = ['gt',0];
                $condition['a.ruku_count'] = ['exp',' != a.jian_count'];
            }elseif ($type == 2){ //已配送
                $condition['a.jian_count'] = ['exp',' = a.ruku_count'];
                $condition['a.ruku_count'] = ['gt',0];
            }

            if($this->begin && $this->end && $user_id != 22687){
                $condition['a.add_time'] = array('between',"$this->begin,$this->end");
            }


            if ($user_id != 22687){
                $condition['a.store_id'] = $store['store_id'];
            }



            $count = M('order a')
                ->join('ty_users b on a.user_id=b.user_id','LEFT')
                ->where($condition)->count();

            $Page = new Page($count, 20);
            $Page->firstRow = $p * $Page->listRows;


            //获取订单列表
            $orderList = M('order a')
                ->field('a.order_id,a.user_id,a.order_sn,b.company,b.mobile,a.driver_id,a.driver_time,a.pay_status,b.company_address,order_amount,jian_count,a.add_time')
                ->join('ty_users b on a.user_id=b.user_id','LEFT')
                ->where($condition)
                ->limit("$Page->firstRow,$Page->listRows ")
                ->order('a.order_id desc')->select(); //过滤获取主订单



            foreach($orderList as $key=>$v) { //整理子单

                $order_goods = M('order_goods a')->join('ty_goods b ON a.goods_id = b.goods_id')->field('a.goods_name,(a.member_goods_price  * a.goods_num) as xiaoji,b.original_img,a.member_goods_price,a.goods_num,a.spec_key_name')->where(['order_id'=>$v['order_id']])->select();

                foreach ($order_goods as $kk=>$vv){
                    $order_goods[$kk]['xiaoji'] = sanwei($vv['xiaoji']);
                    $order_goods[$kk]['original_img'] = C('MYOSS')['url'].$vv['original_img'];
                }
                $orderList[$key]['goods'] = $order_goods;
                $orderList[$key]['add_time'] = date('Y-m-d H:i',$v['add_time']);

                if(!empty($v['driver_time'])){
                    $orderList[$key]['driver_time'] = date('Y-m-d H:i:s',$v['driver_time']);
                }else{
                    $orderList[$key]['driver_time'] = '未配送';
                }
                $orderList[$key]['rucount'] = M('order_jian')->where(['order_id'=>$v['order_id']])->count();
            }

            exit(json_encode(array("status"=>1,'msg'=>'获取成功','data'=>$orderList,'extra'=>['begin'=>date('Y-m-d H:i',$this->begin),'end'=>date('Y-m-d H:i',$this->end)])));

        }else{
            exit(json_encode(array("status"=>'-1','msg'=>'你不是供货商')));
        }
    }


    /**
     * 开启扫码入库功能
     * @return void
     */
    public function qrOpenSan()
    {
        $curr_time = I('curr_time');
        $user_id = I('user_id');
        $expired = M('pda_expired')->where(['user_id'=>$user_id])->find();
        if($expired){
            M('pda_expired')->where(['user_id'=>$user_id])->save(['expired'=>15,'add_time'=>$curr_time]);
        }else{
            M('pda_expired')->add(['expired'=>15,'add_time'=>$curr_time,'user_id'=>$user_id]);
        }
        exit(json_encode(array("status"=>'1','msg'=>'成功开启扫码入库模式，15分钟后失效')));
    }

    /**
     * 扫码取货
     * @return void
     */
    public function saveReturn()
    {
        $id = I('id');
        $supplier_id = I('user_id');
        $return = M('return_goods')->where(['id'=>['in',$id]])->find();
        $store = M('store')->where(['user_id'=>$supplier_id])->find();

        if($store['store_id'] != 22687){
            if($store['store_id'] != $return['store_id']){
                exit(json_encode(array("status"=>0,'msg'=>'你不是订单的商家')));
            }
        }

        M('return_goods')->where(['id'=>['in',$id]])->save(['getorder'=>1,'getorder_time'=>date('Y-m-d H:i:s',time())]);
        exit(json_encode(array("status"=>'1','msg'=>'取货成功')));


    }


    /**
     * 供应商手机入库
     * @return void
     */
    public function ruku(){
        $mobile_san = I('mobile_san');
        if($mobile_san){  //by sofwu 手机扫码入库
            $supplier_id = I('user_id');
            $pda_expired = M('pda_expired')->where(['user_id'=>$supplier_id])->find();
            $store = M('store')->where(['user_id'=>$supplier_id])->find();
            if(!$pda_expired && !$store['open_san']){
                exit(json_encode(array("status"=>0,'msg'=>'你还没有开启扫码入库模式')));
            }
            $expired = $pda_expired['expired'];
            $expired_time = $pda_expired['add_time'];
            $san_time = strtotime('+'.$expired.' minutes',strtotime($expired_time));
            $now = time();
            if($san_time < $now && !$store['open_san']){
                exit(json_encode(array("status"=>0,'msg'=>'启扫码入库模式已经超时')));
            }
        }
        $order_id=I("order_id");
        $ruku_num=I("ruku_num");
        $pda_name_ruku=I("pda_name_ruku");
        $pda_pd2=M('pda')->where('pda_name="'.$pda_name_ruku.'"')->find();
        if(!$pda_pd2){
            exit(json_encode(array("status"=>0,'msg'=>'未认证设备')));
        }
        $pda_pd=M('pda')->where('pda_name="'.$pda_name_ruku.'"')->getField('fenbu_id'); //0广佛，1其他分部
        $basic=tpCache("basic");
        $pd=M('order')->where('order_id='.$order_id.' and order_status in (3,5)')->find();
        $order=M('order')->where('order_id='.$order_id)->find();
        if($pd){
            exit(json_encode(array("status"=>1,'msg'=>'此单已取消！')));
        }else{
            $pd_quyu=M('order')->where('order_id='.$order_id)->getField('ufenbu_id');
            if($pda_pd!=0 && $pda_pd!=$pd_quyu){
                exit(json_encode(array("status"=>0,'msg'=>'此单不是该区域！')));
            }
            if($store['store_id'] != 22687){
                if($store['store_id'] != $order['store_id']){
                    exit(json_encode(array("status"=>0,'msg'=>'你不是订单的商家')));
                }
            }

        }
    	$timestamp = strtotime('today '.$basic['not_ruku_time']);
		if($order['add_time'] > $timestamp){
				exit(json_encode(array("status"=>0,'msg'=>'此单明天扫码，禁止扫码！')));
		}

        
        $fast_ruku_time = $basic['fast_ruku_time'];
        $slow_ruku_time = $basic['slow_ruku_time'];
        $now = time();
        if($fast_ruku_time && $slow_ruku_time) {
            $fast_time = explode('-', $fast_ruku_time);
            $slow_time = explode('-', $slow_ruku_time);
            $fast_start_time = strtotime($fast_time[0]);
            $fast_end_time = strtotime($fast_time[1]);
            $slow_start_time = strtotime($slow_time[0]);
            $slow_end_time = strtotime($slow_time[1]);
            $fast_flag = M('order a')
                ->join('ty_users b ON a.user_id = b.user_id', 'LEFT')
                ->where(['a.order_id' => $order_id])->getField('b.fast_flag');
            if ($fast_flag) {
                if (($now > $fast_start_time) && ($now < $fast_end_time)) {

                    exit(json_encode(array("status"=>0,'msg'=>'快线订单禁止入库!')));
                }
            } else {
                if (($now > $slow_start_time) && ($now < $slow_end_time)) {

                    exit(json_encode(array("status"=>0,'msg'=>'订单禁止入库!')));
                }
            }
        }

        //判断总部和分部字段
        $z=  '';

        $orders=M('order_jian a')
            ->field('a.*,b.order_sn,b.consignee,b.jian_count')
            ->join('ty_order b on a.order_id=b.order_id')
            ->where('a.order_id='.$order_id.' and a.'.$z.'status_r=0 and a.'.$z.'ruku_num='.$ruku_num)->find();
        $ruku_time = strtotime(date("Y-m-d H:i:s"));
        if($orders){
            M('order_jian')
                ->where('order_id='.$order_id.' and '.$z.'status_r=0 and '.$z.'ruku_num='.$ruku_num)
                ->save([
                    $z.'pda_name_ruku'=>$pda_name_ruku,
                    $z.'ruku_time'=>$ruku_time,
                    $z.'status_r'=>'1',
                    'status_c'=> !empty($pda_pd) ? '1' : '0'
                ]);

            M('order')->where('order_id='.$order_id)->setInc('ruku_count');
            M('users_price')->where('order_id='.$order_id)->setField(['status'=>1]);
            $ruku_order = M('order')->where('order_id='.$order_id)->find();
            if($ruku_order['ruku_count'] >$ruku_order['jian_count']){
                M('order')->where('order_id='.$order_id)
                    ->save([
                        'ruku_count'=>$ruku_order['jian_count'],
                    ]);
            }
            if($ruku_order['jian_count'] == $ruku_order['ruku_count']){  //判断是否入库齐全才变已发货订单，司机待配送单那里才会有订单，不齐全的都会在异常订单
                M('order')->where('order_id='.$order_id)
                    ->save([
                        'order_status'=>1,
                        'shipping_status'=>1,
                        'ruku_last_time'=>$ruku_time
                    ]);
            }
            exit(json_encode(array("status"=>1,'msg'=>'入库成功')));
        }else{
            exit(json_encode(array("status"=>0,'msg'=>'此单已经入库！')));
        }

    }

}